package com.chookss.home.studyPlan;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.logContacts.ContactsLogChoiceActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.view.CircleImageView;
import com.chookss.view.RoundCornerImageView;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StudyPlanAddActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.iv)
    RoundCornerImageView iv;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvInit)
    TextView tvInit;
    @BindView(R.id.edTitle)
    EditText edTitle;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.tvStartTime)
    TextView tvStartTime;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private String startTime = "", endTime = "";
    private String title, describe, resourceId, picUrl, time, size;//
    private MyContactEntityAdapter adapter;
    private List<ContactEntity> selectList = new ArrayList<>();
    private int resourceType = 5;// 任务类型（1-小视频 2-长视频 3-集合 4-课程 5 资料）
    private static int SOURSE=6;//选员工所用标识
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_study_plan_add);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this,"1","04");
        MyApp.contactEntityLogList.clear();
        commonTitleTxt.setText("加入学习任务");
        commonRightTxt.setText("确定");
        commonRightTxt.setVisibility(View.VISIBLE);
        title = getIntent().getStringExtra("title");
        describe = getIntent().getStringExtra("describe");
        picUrl = getIntent().getStringExtra("picUrl");
        time = getIntent().getStringExtra("time");
        size = getIntent().getStringExtra("size");
        resourceId = getIntent().getStringExtra("resourceId");
        resourceType = getIntent().getIntExtra("resourceType", 2);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        ;
        Date date = new Date(System.currentTimeMillis());
        startTime = simpleDateFormat.format(date);
        endTime = Utils.addDate();
        tvStartTime.setText(startTime);
        tvEndTime.setText(endTime);
        ContactEntity contactEntity=new ContactEntity();
        contactEntity.setEmployeeCode("0");
        selectList.add(contactEntity);
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 6);
        recyclerView.setLayoutManager(gridLayoutManager1);
        adapter = new MyContactEntityAdapter(R.layout.item_log_choice, this, selectList);
        recyclerView.setAdapter(adapter);
        tvTitle.setText(title);
        edTitle.setText(title);
        edContent.setText(describe);
        if (resourceType == 3) {
            Glide.with(this).load(R.drawable.wdzs_jh).into(iv);
            tvInit.setVisibility(View.GONE);

        } else if (resourceType == 4) {
            Glide.with(this).load(R.drawable.wdzs_kc).into(iv);
            tvInit.setVisibility(View.GONE);

        } else if (resourceType == 5) {
            Glide.with(this).load(R.drawable.wdzs_zl).into(iv);
            tvInit.setText(size);

        } else {
            GlideUtils.loadCustomRound(this, picUrl, iv, 4);
            tvInit.setText(Utils.changeTime(time));
        }
    }

    private void saveData() {
        List<Map<String, String>> employeeList = new ArrayList<>();
        List<Map<String, String>> taskDetailBeanList = new ArrayList<>();
        for (int i = 0; i < selectList.size() - 1; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("employeeCode", selectList.get(i).getEmployeeCode());
            map.put("employeeName", selectList.get(i).getEmployeeName());
            employeeList.add(map);
        }
        Map<String, String> taskDetailMap = new HashMap<>();
        taskDetailMap.put("connectType", resourceType + "");
        taskDetailMap.put("connectCodes", resourceId);
        taskDetailBeanList.add(taskDetailMap);
        Map<String, Object> map = new HashMap<>();
        map.put("taskName", edTitle.getText().toString());
        map.put("taskDesc", edContent.getText().toString());
        map.put("effTime", tvStartTime.getText().toString());
        map.put("invalidTime", tvEndTime.getText().toString());
        map.put("limitTimeLength", "1");
        map.put("dayCount", (Utils.daysBetween(tvStartTime.getText().toString(), tvEndTime.getText().toString())+1)+"");
        map.put("employees", XJson.listToJsArrays(employeeList));
        map.put("taskDetailBeanList", XJson.listToJsArrays(taskDetailBeanList));
        MyHttpRequest.postRequestJson(Urls.addStudyTask, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("加入成功");
                        MyApp.contactEntityLogList.clear();
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    @OnClick({R.id.common_title_back, R.id.common_right_txt, R.id.llStartTime, R.id.llEndTime})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                if (Utils.isNull(edTitle.getText().toString())) {
                    MyToast.show("请输入学习任务名称");
                    return;
                }
                if (Utils.isNull(edContent.getText().toString())) {
                    MyToast.show("请输入学习任务描述");
                    return;
                }
                if (Utils.isNull(tvEndTime.getText().toString())) {
                    MyToast.show("请选择结束时间");
                    return;
                }
                if (!Utils.isNull(tvStartTime.getText().toString())) {
                    if (Utils.getTimeCompareSize(tvStartTime.getText().toString(), tvEndTime.getText().toString()) == 1) {
                        MyToast.show("结束时间不能小于起始时间");
                        return;
                    }
                }
                if (Utils.isNull(tvStartTime.getText().toString())) {
                    MyToast.show("请选择起始时间");
                    return;
                }
                if (!Utils.isNull(tvEndTime.getText().toString())) {
                    if (Utils.getTimeCompareSize(tvStartTime.getText().toString(), tvEndTime.getText().toString()) == 1) {
                        MyToast.show("结束时间不能小于起始时间");
                        return;
                    }
                }
                if (selectList.size() <= 1) {
                    MyToast.show("请选择员工");
                    return;
                }
                saveData();
                break;
            case R.id.llStartTime:
                if (tvStartTime == null) {
                    return;
                }
                showDatePickDialog(tvStartTime.getText().toString(), 0);
                break;
            case R.id.llEndTime:
                if (tvStartTime == null) {
                    return;
                }
                showDatePickDialog(tvEndTime.getText().toString(), 1);
                break;
        }
    }

    private void showDatePickDialog(String curDate, int type) {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        int year = 0, month = 0, day = 0;
        try {
            if (Utils.isNull(curDate)) {
                year = calendar.get(Calendar.YEAR);
                month = calendar.get(Calendar.MONTH);
                day = calendar.get(Calendar.DAY_OF_MONTH);
            } else {
                year = Integer.parseInt(curDate.substring(0, curDate.indexOf("-")));
                month = Integer.parseInt(curDate.substring(curDate.indexOf("-") + 1, curDate.lastIndexOf("-"))) - 1;
                day = Integer.parseInt(curDate.substring(curDate.lastIndexOf("-") + 1, curDate.length()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
        }
        //构建一个日期对话框，该对话框已经集成了日期选择器
        //DatePickerDialog的第二个构造参数指定了日期监听器
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String choiceMonth = "0", choiceDay = " 0";
                if (month + 1 > 9) {
                    choiceMonth = (month + 1) + "";
                } else {
                    choiceMonth = "0" + (month + 1);
                }
                if (dayOfMonth > 9) {
                    choiceDay = dayOfMonth + "";
                } else {
                    choiceDay = "0" + dayOfMonth;
                }
                if (type == 0) {
                    tvStartTime.setText(year + "-" + choiceMonth + "-" + choiceDay);
                } else {
                    if (Utils.getTimeCompareSize(tvStartTime.getText().toString(),year + "-" + choiceMonth + "-" + choiceDay) == 1) {
                        MyToast.show("结束时间不能小于起始时间");
                        return;
                    } else {
                        tvEndTime.setText(year + "-" + choiceMonth + "-" + choiceDay);
                    }
                }

            }
        },
                year,
                month,
                day);
        //把日期对话框显示在界面上
        dialog.show();
    }
    class MyContactEntityAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {
        private Context context;

        public MyContactEntityAdapter(int layoutResId, Context context,
                                      @io.reactivex.annotations.Nullable List<ContactEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity item) {
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            ImageView ivAdd = helper.getView(R.id.ivAdd);
            TextView tvName = helper.getView(R.id.tvName);
            if (helper.getItemPosition() == selectList.size() - 1) {
                ivAdd.setVisibility(View.VISIBLE);
                ivHead.setVisibility(View.GONE);
                tvName.setVisibility(View.GONE);
            } else {
                ivAdd.setVisibility(View.GONE);
                if ("0".equals(item.getType())) {
//                    部门
                    ivHead.setVisibility(View.GONE);
                    tvName.setVisibility(View.VISIBLE);
                    tvName.setText(item.getEmployeeName());
                } else {
                    //员工
                    ivHead.setVisibility(View.VISIBLE);
                    tvName.setVisibility(View.GONE);
                    GlideUtils.loadAvatar(StudyPlanAddActivity.this, item.getHeadPhotoThumbUrl(),
                            ivHead);
                }
            }
            ivAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(StudyPlanAddActivity.this, ContactsLogChoiceActivity.class);
                    intent.putExtra("source", SOURSE+"");
                    startActivity(intent);
                }
            });
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("ChoiceContacts_Ok_"+SOURSE)) {
                if (recyclerView == null) {
                    return;
                }
                if (MyApp.contactEntityLogList.size() > 0) {
                    List<String> orgCodeList = new ArrayList<>();
                    List<String> employeeCodeList = new ArrayList<>();
                    List<ContactEntity> serverList = new ArrayList<>();
                    for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                        KLog.i(MyApp.contactEntityLogList.get(i).getEmployeeName()+"===");
                        ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                        if (!contactEntity.isHalfSelect()) {
                            if (contactEntity.getType().equals("0")) {
                                orgCodeList.add(contactEntity.getEmployeeCode());
                            } else {
                                serverList.add(contactEntity);
                                employeeCodeList.add(contactEntity.getEmployeeCode());
                            }
                        }
                    }
                    if (orgCodeList.size() > 0) {
                        getServerData(orgCodeList, employeeCodeList);
                    } else {
                        //没有组织，
                        selectList.clear();
                        selectList.addAll(serverList);
                        setServerData();
                    }
                }else{
                    //不选任何人
                    selectList.clear();
                    setServerData();
                }
            }
        }
    }
    private void getServerData(List<String> orgCodeList, List<String> employeeCodeList) {
        //把选择的部门里面的人全部查出来
        Map<String, Object> map = new HashMap<>();
        map.put("orgCode", JSON.toJSONString(orgCodeList));
        map.put("employeeCode", JSON.toJSONString(employeeCodeList));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.getSelectedEmployee, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        List<ContactEntity> serverList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                            ContactEntity contactEntity = new ContactEntity();
                            contactEntity.setEmployeeName(jsonObject2.getString("employeeName"));
                            contactEntity.setEmployeeCode(jsonObject2.getString("employeeCode"));
                            contactEntity.setHeadPhotoThumbUrl(jsonObject2.getString("headPhotoThumbUrl"));
                            contactEntity.setType("1");
                            contactEntity.setEmpNum("0");
                            contactEntity.setReviewerFlag("0");
                            contactEntity.setHalfSelect(false);
                            contactEntity.setSelect(false);
                            serverList.add(contactEntity);
                        }
                        selectList.clear();
                        selectList.addAll(serverList);
                        setServerData();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }

    private void setServerData() {
        if (recyclerView == null) {
            return;
        }
        ContactEntity contactEntity=new ContactEntity();
        contactEntity.setEmployeeCode("0");
        selectList.add(contactEntity);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (edContent != null) {
            Utils.hideInputKeyboard(this, edContent);
        }

    }
}
